package org.steven.crm.core.test.utils;

import com.luciad.imageio.webp.WebPWriteParam;

import javax.imageio.IIOImage;
import javax.imageio.ImageIO;
import javax.imageio.ImageWriteParam;
import javax.imageio.ImageWriter;
import javax.imageio.stream.FileImageOutputStream;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

/**
 * @Author wuzw
 * @Date 2024/3/17 18:02
 * @Version 1.0
 */
public class ImageConverter {
    private static String srcDirPath = "C:\\Users\\wuzw\\Desktop\\public";

    public static void main(String[] args) throws Exception {
        File srcDir = new File(srcDirPath);
        convertFile(srcDir);
    }

    private static void convertFile(File file) throws Exception {
        String fileName = file.getName();
        if (file.isFile()) {
            if (isImage(file)) {
                String newFileName = fileName + ".webp";
                convertJpegToWebpLossless(file, new File(file.getParent() + File.separator + newFileName));
            }
        } else {
            File[] subFiles = file.listFiles();
            for (File subFile : subFiles) {
                convertFile(subFile);
            }
        }
    }

    private static boolean isImage(File file) {
        String fileName = file.getName();
        if (fileName.toLowerCase().endsWith(".png")
                || fileName.toLowerCase().endsWith(".jpg")
                || fileName.toLowerCase().endsWith(".gif")
                || fileName.toLowerCase().endsWith(".jpeg")
        ) {
            return true;
        }

        return false;
    }

    private static void convertJpegToWebpLossless(File srcFile, File targetFile) {
        System.out.println("convert file " + srcFile.getAbsolutePath());
        try {
            BufferedImage image = ImageIO.read(srcFile);
            ImageWriter writer = ImageIO.getImageWritersByMIMEType("image/webp").next();
            WebPWriteParam writeParam = new WebPWriteParam(writer.getLocale());
            writeParam.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
            /*// 设置无损
            writeParam.setCompressionType(writeParam.getCompressionTypes()[WebPWriteParam.LOSSLESS_COMPRESSION]);*/

            // 设置有损压缩
            writeParam.setCompressionType(writeParam.getCompressionTypes()[WebPWriteParam.LOSSY_COMPRESSION]);
            //设置 80% 的质量. 设置范围 0-1
            writeParam.setCompressionQuality(0.8f);

            // 保存图片
            writer.setOutput(new FileImageOutputStream(targetFile));
            writer.write(null, new IIOImage(image, null, null), writeParam);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
